package ace.module.upms.core.impl.service.impl;

import ace.cmp.util.model.dto.TreeNode;
import ace.module.security.api.AuthenticationApi;
import ace.module.upms.api.model.dto.UpmsApplicationDto;
import ace.module.upms.core.impl.dao.aggregate.UpmsMenuAggregate;
import ace.module.upms.core.impl.dao.entity.UpmsMenu;
import ace.module.upms.core.impl.dao.repository.UpmsMenuRepository;
import ace.module.upms.core.impl.manager.UpmsApplicationManager;
import ace.module.upms.core.impl.manager.UpmsMenuManager;
import ace.module.upms.core.impl.service.UpmsMenuService;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/8/18 17:42
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UpmsMenuServiceImpl implements UpmsMenuService {
  private final UpmsMenuRepository upmsMenuRepository;
  private final UpmsMenuAggregate upmsMenuAggregate;
  private final AuthenticationApi authenticationApi;
  private final UpmsMenuManager upmsMenuManager;
  private final UpmsApplicationManager upmsApplicationManager;

  @Override
  public List<UpmsMenu> getByCurrentAccount() {
    Long upmsAppId = this.authenticationApi.getCurrentUpmsAppId();
    Long accountId = this.authenticationApi.getAndCheckCurrentAccountId();
    Boolean superAdminFlag = this.authenticationApi.hasSuperAdministratorAuthority();
    if (accountId == null || upmsAppId == null) {
      return new ArrayList<>();
    }
    if (superAdminFlag) {
      return this.upmsMenuRepository.getByUpmsAppIdAndDeleteFlagIsFalse(upmsAppId);
    }
    return this.upmsMenuAggregate.getByUpmsAppIdAndAccountIdAndDeleteFlagIsNot(
        upmsAppId, accountId);
  }

  @Override
  public List<UpmsMenu> getAllByUpmsAppId(Long upmsAppId) {
    return upmsMenuManager.getByUpmsAppIdAndDeleteFlagIsFalse(upmsAppId);
  }

  @Override
  public List<TreeNode<UpmsMenu>> getTreeAllByUpmsAppId(Long upmsAppId) {
    return upmsMenuManager.getTreeByUpmsAppIdAndDeleteFlagIsFalse(upmsAppId);
  }

  @Override
  public List<TreeNode<UpmsMenu>> getAllByOutTypeAndOutId(String outType, String outId) {
    UpmsApplicationDto upmsApplication =
        this.upmsApplicationManager.getAndCheckDtoByOutTypeAndOutId(outType, outId);
    return this.getTreeAllByUpmsAppId(upmsApplication.getId());
  }
}
